26. Background Jobs

Note

The below information is extensively based in information taken from the PowerShell® Notes for Professionals book. I plan to extend this information based on my day to day usage of the language.

Jobs were introduced in PowerShell 2.0 and helped to solve a problem inherent in the command-line tools. In a nutshell, if you start a long running task, your prompt is unavailable until the task finishes. As an example of a long running task, think of this simple PowerShell command:

Get-ChildItem -Path c: -Recurse

It will take a while to fetch full directory list of your C: drive. If you run it as Job then the console will get the control back and you can capture the result later on.

26.1: Basic job creation

Start a Script Block as background job:

1
$job = Start-Job -ScriptBlock { Get-Process }

Start a script as background job:

1
$job = Start-Job -FilePath "C:\YourFolder\Script.ps1"

Start a job using Invoke-Command on a remote machine:

1
$job = Invoke-Command -ComputerName "ComputerName" - ScriptBlock { Get-Service winrm} - JobName "WinRM" - ThrottleLimit 16 - AsJob

Start job as a different user (Prompts for password):

1
Start-Job -ScriptBlock { Get-Process } -Credential "Domain\Username"

Or

1
Start-Job -ScriptBlock { Get-Process } -Credential ( Get-Credential )

Start job as a different user (No prompt):

1
2
3
4
5
$username = "Domain\Username"
$password = "password"
$secPassword = ConvertTo-SecureString -String $password -AsPlainText -Force
$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList @($username, $secPassword)
Start-Job -ScriptBlock { Get-Process } -Credential $credentials

26.2: Basic job management

Get a list of all jobs in the current session:

1
Get-Job

Waiting on a job to finish before getting the result:

1
$job | Wait-job | Receive-Job

Timeout a job if it runs too long (10 seconds in this example)

1
$job | Wait-job -Timeout 10

Stopping a job (completes all tasks that are pending in that job queue before ending):

1
$job | Stop-Job

Remove job from current session's background jobs list:

1
$job | Remove-Job

Note : The following will only work on Workflow Jobs.

Suspend a Workflow Job (Pause):

1
$job | Suspend-Job

Resume a Workflow Job:

1
$job | Resume-Job